package com.spzx.test1;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Cook {
    //资源
    Lock lock = new ReentrantLock();
    Condition cookCondition = lock.newCondition();
    Condition cutCondition = lock.newCondition();
    Condition giveCondition = lock.newCondition();
    String status = "cut";


    public void cook(){
        lock.lock();
        while (!status.equals("cook")) {
            try {
                cookCondition.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        }
        System.out.println("炒菜师傅正在炒菜");
        try {
            TimeUnit.SECONDS.sleep(new Random().nextInt(3)+1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("炒菜师傅炒完菜");
        status = "give";
        giveCondition.signal();
        lock.unlock();

    }

    public void cut() {
        lock.lock();
        while (!status.equals("cut")) {
            try {
                cutCondition.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        }
        System.out.println("切菜师傅正在切菜");
        try {
            TimeUnit.SECONDS.sleep(new Random().nextInt(3)+1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("切菜师傅切完菜");
        status = "cook";
        cookCondition.signal();
        lock.unlock();
    }

    public void give() {
        lock.lock();
        while (!status.equals("give")) {
            try {
                giveCondition.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        }
        System.out.println("上菜师傅正在上菜");
        try {
            TimeUnit.SECONDS.sleep(new Random().nextInt(3)+1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("上菜师傅上完菜");
        status="cut";
        cutCondition.signal();
        lock.unlock();


    }



}
